#ifndef __COMM_HPP__
#define __COMM_HPP__ 

#include <iostream>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <string>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>



using namespace std;

#define PATHNAME "."
#define PROJID 0x6666

const int gsize = 4096;//共享内存的大小

//获取key值
key_t getKey()
{
    key_t k = ftok(PATHNAME,PROJID);
    if(k==-1)
    {
        cerr << errno << ":" << strerror(errno) << endl;
        exit(1);
    }
    return k;
}

string toHex(int x)
{
    char buffer[64];
    snprintf(buffer,sizeof(buffer),"0x%x",x);
    return buffer;
}

static int createShmHelper(key_t k, int size, int flag)
{
    int shmid = shmget(k, gsize, flag);
    if(shmid == -1)
    {
        cerr << "error: "<<errno<<":"<<strerror(errno)<<endl;
        exit(2);
    }
    return shmid;
}
//一个进程创建共享内存，一个进程获取
//这里server服务端创建，客户端获取
int createShm(key_t k,int size)
{
    umask(0);
    return createShmHelper(k,size,IPC_CREAT | IPC_EXCL | 0666);
}
int getShm(key_t k,int size)
{
    return createShmHelper(k,size,IPC_CREAT);

}
//关联共享内存
char* attachShm(int shmid)
{
    char* start = (char*)shmat(shmid,nullptr,0);
    return start;
}

//解除关联
void detachShm(char* start)
{
    int n = shmdt(start);
    assert(n!=-1);
    (void)n;
}

//删除共享内存段
void delshm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    assert(n != -1);
    (void)n;
}

#define SERVER 1
#define CLIENT 0

class Init 
{
public:
    Init(int t)
        :type(t)
    {
        key_t k = getKey();//1.获取key值
        //2.创建共享内存
        if(type == SERVER)
            shmid = createShm(k,gsize);//服务端则创建共享内存
        else 
            shmid = getShm(k,gsize);//客户端则获取服务端已创建的共享内存

        //3.关联共享内存
        start = attachShm(shmid);
    }
    char* getStart(){return start;}
    ~Init()
    {
        //4.解除与共享内存的关联
        detachShm(start);
        //5.删除共享内存
        if(type == SERVER)//如果是服务端，则删除共享内存
            delshm(shmid);
    }
private:
    char* start;
    int type;//SERVER or CLIENT 
    int shmid; 
};

#endif
